package com.wp.www.service.impl;

import com.wp.www.entity.order.Order;
import com.wp.www.repository.OrderMapper;
import com.wp.www.service.AccountService;
import com.wp.www.service.OrderService;
import com.wp.www.service.StorageService;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private AccountService accountService;

    @Resource
    private StorageService storageService;

    @GlobalTransactional(name = "create-order",rollbackFor = {Exception.class})
    @Override
    public Integer createOrder(Order order) {
        log.info("*****全局事务xid:{}", RootContext.getXID());

        log.info("*****deduction of goods : {} begins",order.getCommodityCode());
        storageService.reduceStorage(order.getCommodityCode(),order.getCount());
        log.info("*****deduction of goods : {} ends",order.getCommodityCode());

        log.info("****deduction of balance : {} begins",order.getUserId());
        accountService.deductAccount(order.getUserId(),order.getMoney());
        log.info("****deduction of balance : {} ends",order.getUserId());

        int age = 10 /0 ;

        log.info("****order creation begins");
        Integer orderId = orderMapper.createOrder(order);
        log.info("****order : {} creation ends",orderId);
        return orderId;
    }
}
